package com.it.admin.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.admin.AdminUserService;
import com.it.bean.ConstEnum;
import com.it.bean.RestServiceEnum;
import com.it.dao.UserMapper;
import com.it.dao.UserTokenMapper;
import com.it.pojo.User;
import com.it.pojo.UserToken;
import com.it.pojo.params.RegisterQuery;
import com.it.pojo.params.user.UserListQuery;
import com.it.pojo.vo.AdminUserVO;
import com.it.pojo.vo.user.AdminUserEditVO;
import com.it.pojo.vo.user.UserInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AdminUserServiceImpl implements
        AdminUserService {
    @Resource
    private UserMapper usersMapper;

    @Resource
    private UserTokenMapper userTokenMapper;

    @Override
    public String login(String username, String password) {
        String md5Pwd = SecureUtil.md5(password + ConstEnum.PWD_SALT.getResult());
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getUsername, username);
        User user = usersMapper.selectOne(wrapper);
        if (user == null) {
            return RestServiceEnum.LOGIN_NAME_NOT_EXIST.getResult();
        }
        if (ConstEnum.LOCKED_FLAG.getResult().equals(user.getStatus() + "")) {
            return RestServiceEnum.LOGIN_USER_LOCKED_ERROR.getResult();
        }
//        if (!ConstEnum.USER_TYPE.getResult().equals(user.getType() + "")) {
//            return RestServiceEnum.LOGIN_USER_ADMIN.getResult();
//        }
        String token = getToken(user.getUserId());
        UserToken userToken = userTokenMapper.selectById(user.getUserId());
        // 当前时间
        Date date = new Date();
        Date expireTime = new Date(date.getTime() + 1000 * 60 * 60 * 24);
        if (userToken == null) {
            userToken = new UserToken();
            userToken.setUserId(user.getUserId());
            userToken.setGmtCreate(date);
            userToken.setGmtModified(date);
            userToken.setToken(token);
            // 一天过期
            userToken.setExpireTime(expireTime);
            if (userTokenMapper.insert(userToken) > 0) {
                return token;
            }

        } else {
            userToken.setGmtModified(date);
            userToken.setToken(token);
            // 一天过期
            userToken.setExpireTime(expireTime);
            if (userTokenMapper.updateById(userToken) > 0) {
                return token;
            }
        }
        return RestServiceEnum.LOGIN_USER_ERROR.getResult();
    }

    @Override
    public int register(RegisterQuery registerQuery) {
        synchronized (this) {
            String md5Pwd = SecureUtil.md5(registerQuery.getPassword() + ConstEnum.PWD_SALT.getResult());
            registerQuery.setPassword(md5Pwd);
            User user = new User();
            // 当前时间
            Date date = new Date();
            BeanUtils.copyProperties(registerQuery, user);
            System.out.println("user = " + user);
            user.setGmtCreate(date);
            // 默认头像
            user.setAvatar("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
            user.setGmtModified(date);
            return usersMapper.insert(user);
        }

    }

    @Override
    public Map<String, Object> listUsers(UserListQuery userQuery) {
        Integer limit = userQuery.getLimit();
        Integer start = (userQuery.getPageNum() - 1) * limit;
        String firstDate = null;
        String lastDate = null;
        if (userQuery.getDate().length != 0 && userQuery.getDate() != null) {
            firstDate = userQuery.getDate()[0].substring(0, 10);
            lastDate = userQuery.getDate()[1].substring(0, 10);
        }
        String nickname = userQuery.getNickname();
        if (StringUtils.isNotBlank(nickname)) {
            nickname = "%" + userQuery.getNickname() + "%";
        }
        Integer status = userQuery.getStatus();
        List<User> users = usersMapper.listUser(nickname, status, firstDate, lastDate, start, limit);
        int total = usersMapper.listUserTotal(nickname, status, firstDate, lastDate);
        System.out.println("total = " + total);
        Map<String, Object> map = new HashMap<>();
        List<AdminUserVO> adminUserVOS = copyList(users);

        map.put("total", total);
        map.put("userList", adminUserVOS);
        return map;
    }

    @Override
    public int deleteUserById(Integer userId) {
        return usersMapper.deleteById(userId);
    }

    @Override
    public int saveUser(User user) {
        user.setPassword(SecureUtil.md5(user.getPassword() + ConstEnum.PWD_SALT.getResult()));
        Date date = new Date();
        user.setGmtModified(date);
        user.setGmtCreate(date);
        return usersMapper.insert(user);
    }

    @Override
    public AdminUserEditVO getUserById(Integer userId) {
        User user = usersMapper.selectById(userId);
        AdminUserEditVO adminUserEditVO = new AdminUserEditVO();
        BeanUtils.copyProperties(user, adminUserEditVO);
        return adminUserEditVO;
    }

    @Override
    public int updateUserById(User user) {
//        System.out.println("user = " + user);
        user.setGmtModified(new Date());
        user.setPassword(SecureUtil.md5(user.getPassword() + ConstEnum.PWD_SALT.getResult()));
        return usersMapper.updateById(user);
    }

    @Override
    public UserInfoVO getUserByToken(String token) {
        UserInfoVO userInfoVO = usersMapper.getUserByToken(token);
        return userInfoVO;
    }

    @Override
    public int logout(Integer userId) {
        LambdaQueryWrapper<UserToken> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserToken::getUserId, userId);
        return userTokenMapper.delete(wrapper);
    }

    private AdminUserVO copy(User user) {
        AdminUserVO adminUserVO = new AdminUserVO();
        BeanUtils.copyProperties(user, adminUserVO);
        return adminUserVO;
    }

    private List<AdminUserVO> copyList(List<User> userList) {
        List<AdminUserVO> list = new ArrayList<>();
        for (User user : userList) {
            list.add(copy(user));
        }
        return list;
    }


    private String getToken(Integer userId) {

        String token = SecureUtil.md5(System.currentTimeMillis() + "" + userId);
        return token;


    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        String date = "2022-02-07T16:00:00.000Z";
        String date = "2022-02-07";
        Date parse = simpleDateFormat.parse(date);
        System.out.println("parse = " + parse);
    }
}
